<template>
  <view class="yuongjin">
    <view class="sum">
      <view class="sumItem">
        <view>全部余额</view>
        <view>{{ listData.other.total }}</view>
      </view>
      <view class="sumItem">
        <view>可使用</view>
        <view>{{ listData.other.settled }}</view>
      </view>
      <view class="sumItem">
        <view>冻结中</view>
        <view>{{ listData.other.wait }}</view>
      </view>
    </view>

    <u-tabs bg-color="#f8f8f8" :active-color="themeColor1" name="cate_name" count="cate_count" :list="list"
      :is-scroll="false" :current="current" @change="change"></u-tabs>

    <view style="margin-bottom: 100px;margin-top: 10px;" v-show="!current">
      <view v-if="listData.list.length > 0">
        <view class="list" :style="{ border: `1px solid ${themeColor1}` }" v-for="item in listData.list">
          <view>
            <view class="flex flex_between" style="margin-bottom: 10px;">
              <view class="color1 flex flex_a_center"><span class="color2">{{ item.type_title }}</span></view>
            </view>
            <view class="flex flex_between settle">
              <view class="color1 flex flex_a_end text">
                <span class="color2">{{ item.create_time }}</span>
              </view>
            </view>
          </view>

          <view class="flex flex_between settle">
            <view class="color1 flex flex_a_end text"><span class="color2">+</span><span class="color2 num">{{
              item.commission }}</span></view>
          </view>

        </view>
      </view>
      <ns-empty v-else :isIndex="false" text="暂无余额明细"></ns-empty>
    </view>

    <view v-show="current" style="margin-bottom: 100px;margin-top: 10px;">
      <page-meta :page-style="themeColor"></page-meta>
      <view style="position: relative;">
        <view class="tab color-bg">
          <view class="tab-left">
            <picker mode="date" :value="searchType.date" @change="bindDateChange" fields="month">
              <view class="uni-input">
                {{ date }}
                <text class="iconfont icon-iconangledown"></text>
              </view>
            </picker>
          </view>
          <!-- <view class="tab-right">
            <picker @change="bindPickerChange" :value="balanceIndex" :range="balanceType" class="picker"
              range-key="label">
              <text class="desc uni-input">{{ balanceType[balanceIndex].label }}</text>
              <text class="iconfont icon-iconangledown"></text>
            </picker>
          </view> -->
        </view>
        <mescroll-uni @getData="getData" ref="mescroll">
          <block slot="list">
            <!-- 明细列表 -->
            <block v-if="dataList.length > 0">
              <view class="detailed-wrap ">

                <!-- <view class="balances" v-for="(item, index) in dataList" :key="index">
                  <view class="balances-info" @click="toFromDetail(item)">
                    <text class="title">{{ item.type_name }}</text>
                    <text>{{ item.remark }}</text>
                    <text>{{ $util.timeStampTurnTime(item.create_time) }}</text>
                  </view>
                  <view class="balances-num">
                    <text :class="item.account_data > 0 ? 'color-base-text' : ''">{{ item.account_data > 0 ? '+' +
                      item.account_data : item.account_data }}</text>
                  </view>
                </view> -->

                <view class="list" :style="{ border: `1px solid ${themeColor1}` }" v-for="(item, index) in dataList"
                  :key="index">
                  <view>
                    <view class="flex flex_between" style="margin-bottom: 10px;">
                      <view class="color1 flex flex_a_center"><span class="color2">{{ item.type_name }}</span></view>
                    </view>
                    <view class="flex flex_between settle">
                      <view class="color1 flex flex_a_end text">
                        <span class="color2">{{ $util.timeStampTurnTime(item.create_time) }}</span>
                      </view>
                    </view>
                  </view>

                  <view class="flex flex_between settle">
                    <view class="color1 flex flex_a_end text"><span class="color2 num">{{ item.account_data > 0 ? '+' +
                      item.account_data : item.account_data }}</span></view>
                  </view>
                </view>

              </view>
            </block>
            <block v-else><ns-empty :isIndex="false" text="暂无余额明细"></ns-empty></block>

            <!-- 无明细列表 -->
          </block>
        </mescroll-uni>
        <loading-cover ref="loadingCover"></loading-cover>
      </view>
    </view>

    <!-- <view class="end_b" >
      <button @click="submit"  class="complete_btn" >
        分享人海报
      </button>
    </view> -->

    <view class="end_b">
      <!-- <button @click="setCank(1)" class="complete_btn">
        余额提现
      </button>
      <button @click="setCank(2)" class="complete_btn">
        余额互转
      </button> -->

      <button @click="setCank(1)" :style="{ 'backgroundColor': themeColor1, 'color': btn_text_color }" class="complete_btn"
        type="primary" size="mini">
        余额提现
      </button>
      <button @click="setCank(2)" :style="{ 'backgroundColor': themeColor1, 'color': btn_text_color }" class="complete_btn"
        type="primary" size="mini">
        余额互转
      </button>

    </view>

    <u-modal v-model="show" @cancel="cancel" @confirm="confirm" show-cancel-button title="请输入转入账号的手机号码"
      confirm-color="#ec692b">
      <view class="slot-content">
        <u-field border-top v-model="mobile" label-width="0" placeholder="请填写手机号"></u-field>
        <u-field border-top v-model="balance" label-width="0" @input="input" placeholder="请填写转移金额"></u-field>
      </view>
    </u-modal>
    <!-- 海报 -->
    <uni-popup ref="Poster" type="center">
      <view class="member-code-popup">
        <!-- 海报 -->
        <image show-menu-by-longpress='1' style="height: 300px; padding: 20rpx;box-sizing: border-box;" mode="aspectFit"
          :src="posterUrl" @error="imageError"></image>
        <view class="popup-bottom"><text class="iconfont iconfont-delete icon-close-guanbi" @click="closePoster()"></text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import uniPopup from '@/components/uni-popup/uni-popup.vue';
import balanceDetail from '@/pages_tool/member/balance_detail.vue';

export default {
  components: {
    uniPopup,
    balanceDetail
  },
  mixins: [],
  data() {
    const currentDate = this.getDate({
      format: true
    });
    return {
      themeColor1: '',
      btn_text_color: '',
      page: 1,
      page_size: 10,
      listData: {},
      posterUrl: '',
      show: false,
      mobile: '',
      balance: '',
      list: [
        {
          name: '佣金明细'
        }, {
          name: '余额明细'
        }],
      current: 0,


      dataList: [],
      statusList: [{ name: '全部', id: '0' }, { name: '收入', id: '1' }, { name: '支出', id: '2' }],
      scrollInto: '',
      orderStatus: '0',
      date: currentDate,
      searchType: {
        from_type: 0,
        date: ''
      },
      balanceType: [
        {
          label: '全部',
          value: '0'
        }
      ], //积分类型
      balanceIndex: 0,
      related_id: 0
    }
  },
  onShow() {
    if (!uni.getStorageSync('token')) {
      this.$refs.login.open('/pages_tool/member/balance');
    }
    this.agentlists()
  },
  onLoad(option) {

    let theme = uni.getStorageSync('theme_style');
    this.themeColor1 = `${theme.main_color}`;
    this.btn_text_color = `${theme.btn_text_color}`;

    if (option.group_id) this.related_id = option.group_id ? option.group_id : 0;
    if (option.from_type) this.searchType.from_type = option.from_type;
    if (option.related_id) this.related_id = option.related_id ? option.related_id : 0;
    if (option.status) this.orderStatus = option.status;
    this.getbalanceType();
  },
  onReachBottom() {
    if (this.listData.list.length == this.listData.count) {
      return;
    }
    this.page++
    this.agentlists()
  },
  methods: {
    bindDateChange: function (e) {
      var temp = e.target.value;
      var tempArr = temp.split('-');
      this.date = tempArr[0] + '年' + tempArr[1] + '月';
      this.searchType.date = e.target.value;
      this.$refs.mescroll.refresh();
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 60;
      } else if (type === 'end') {
        year = year + 2;
      }
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}年${month}月`;
    },
    bindPickerChange(e) {
      this.balanceIndex = e.detail.value;
      this.searchType.from_type = this.balanceType[this.balanceIndex].value;
      this.$refs.mescroll.refresh();
    },
    //获取分类类型
    getbalanceType() {
      this.$api.sendRequest({
        url: '/api/memberaccount/fromType',
        success: res => {
          let balanceType = Object.assign(res.balance, res.balance_money), typeArr = [{ label: '全部', value: '0' }];
          for (var index in balanceType) {
            typeArr.push({ label: balanceType[index].type_name, value: index })
          }
          this.balanceType = typeArr;
        }
      });
    },
    ontabtap(e) {
      let index = e.currentTarget.dataset.current;
      this.orderStatus = this.statusList[index].id;
      this.$refs.mescroll.refresh();
    },
    getData(mescroll) {
      this.$api.sendRequest({
        url: '/api/memberaccount/page',
        data: {
          page_size: mescroll.size,
          page: mescroll.num,
          account_type: 'balance,balance_money',
          from_type: this.searchType.from_type,
          date: this.searchType.date,
          related_id: this.related_id
        },
        success: res => {
          let newArr = [];
          let msg = res.message;
          if (res.code == 0 && res.data) {
            newArr = res.data.list;
          } else {
            this.$util.showToast({ title: msg });
          }
          mescroll.endSuccess(newArr.length);
          //设置列表数据
          if (mescroll.num == 1) {
            this.dataList = []; //如果是第一页需手动制空列表
            this.related_id = 0;
          }
          this.dataList = this.dataList.concat(newArr); //追加新数据
          if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
        },
        fail: res => {
          mescroll.endErr();
          if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
        }
      });
    },
    toFromDetail(item) {
      if (item.from_type == 'order' && !isNaN(parseInt(item.type_tag))) {
        this.$util.redirectTo('/pages/order/detail', { order_id: item.type_tag });
      } else if (item.from_type == 'refund' && parseInt(item.type_tag) != 0) {
        this.$util.redirectTo('/pages/order/detail', {
          order_id: item.type_tag
        });
      }
    },

    change(index) {
      this.current = index;
    },
    input(value) {
      console.log('输入', value);
      console.log(!/^[0-9]*$/.test(value));
      console.log(value <= 0);
      // if (!/^[0-9]*$/.test(value)) {
      //   this.balance = 0
      //   console.log('输入',this.balance);
      //   return;
      // }
      // if(value <= 0){
      //   this.balance = 0
      //   console.log('输入',this.balance);
      //   return;
      // }
      // this.balance = value

    },
    cancel() {
      this.mobile = '';
      this.balance = '';
    },
    isValidPositiveNumber(str) {
    // 使用正则表达式检查字符串是否为数字（包括小数），并且最多两位小数
    const regex = /^[0-9]+(\.[0-9]{1,2})?$/;
    if (regex.test(str)) {
        // 如果正则表达式测试通过，尝试将字符串转换为数字
        const num = parseFloat(str);
        // 检查转换后的数字是否大于0
        return num > 0;
    }
    return false;
},
    confirm() {
      if (this.mobile == '') {
        this.$util.showToast({ title: '请输入转入账号的手机号码' });
        this.show = true
        return;
      }
      if (this.balance == '') {
        this.$util.showToast({ title: '请输入转入账号的金额' });
        this.show = true
      }
      // balance 只能为数字，并且大于0
      if ( !this.isValidPositiveNumber(this.balance)) {
        this.$util.showToast({ title: '转入金额只能为数字，并且大于0' });
        this.show = true
        return;
      }

      this.$api.sendRequest({
        url: '/api/member/memberBalanceTrade',
        data: {
          mobile: this.mobile,
          balance: this.balance,
        },
        success: res => {
          console.log(res);
          this.cancel()
          if (res.code == 0) {
            this.listData = {}
            this.agentlists()
            this.$util.showToast({ title: '成功转入' });
          } else {
            this.$util.showToast({ title: res.message });
            this.show = true
          }
        }
      })
    },
    setCank(type) {
      if (type == 1) {
        this.$util.redirectTo('/pages_tool/member/apply_withdrawal')
      } else {
        this.show = true;
      }
    },
    imageError() {

      this.posterUrl = ''
      this.$forceUpdate();
    },
    closePoster() {
      this.$refs.Poster.close();
    },
    agentlists() {
      this.$api.sendRequest({
        url: '/api/member/teamCommissionLog',
        data: {
          page: this.page,
          page_size: this.page_size
        },
        success: res => {
          console.log(res.data, 'res.data');
          if (this.page == 1) {
            this.listData = res.data
          } else {
            this.listData.list = [...this.listData.list, ...res.data.list]
          }
        }
      });
    },
    submit() {
      uni.showLoading({
        title: '加载中...',
        mask: true
      });
      this.$api.sendRequest({
        url: '/api/member/teamCommissionLog',
        data: {
        },
        success: res => {
          uni.hideLoading();
          console.log(res, 'res');
          this.posterUrl = res.data.url
          this.$refs.Poster.open();
        }
      });
    }
  },
  // onShareTimeline() {
  //   return {
  //     title: '鹏城快享',
  //     query: `source_member=${uni.getStorageSync("user_id")}`,
  //     imageUrl: ""
  //   }
  // },
  // onShareAppMessage() {
  //   return {
  //     title: "鹏城快享",
  //     path: `/pages/index/index?source_member=${uni.getStorageSync("user_id")}`,
  //     imageUrl: ''
  //   }
  // },
};
</script>

<style lang="scss" >
@import '@/common/css/diy.scss';

.tab {
  position: absolute;
}

.member-code-popup .popup-bottom {
  display: flex;
  align-items: center;
  justify-content: center;
  background: none !important;

}

.member-code-popup .popup-bottom .iconfont-delete {
  font-size: 48rpx;
  margin: 20rpx;
  // color: #fff;
}

.end_b {
  position: fixed;
  right: 0;
  left: 0;
  bottom: 0;
  height: 180rpx;
  // background-color: #fff;
  padding: 30rpx 20rpx;
  display: flex;
  gap: 10px;

  .complete_btn {
    width: 100%;
    border-radius: 40rpx;
    width: 100%;
    height: 70rpx;
    font-size: 28rpx;
    line-height: 70rpx;
    margin: 0;
    // background-color: $base-color;
    // color: var(--btn-text-color);
  }
}

.flex {
  display: flex;
}

.flex_1 {
  flex: 1;
}

.color1 {
  color: #666;
}

.color2 {
  color: #201003;
}

.flex_between {
  justify-content: space-between;
}

.flex_a_center {
  align-items: center;
}

.flex_a_end {
  align-items: flex-end;
}

.slot-content {
  padding: 20px 10px;
}

.yuongjin {
  margin: 20rpx 30rpx;
  padding-bottom: 30px;

  .sum {
    background-color: #201003;
    padding: 30rpx 0;
    border-radius: 9px;
    display: flex;
    margin-bottom: 30rpx;

    .sumItem {
      flex: 1;
      text-align: center;

      &:nth-child(2) {
        border-right: 1px solid #fff;
        border-left: 1px solid #fff;
      }

      &>view {
        color: #fff;
      }

      view:nth-child(2) {
        font-weight: bold;
        font-size: 22px;
        margin-top: 10px;
      }
    }
  }

  .list {
    border-radius: 9px;
    background-color: #fff;
    padding: 30rpx 25rpx;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    // border: 1px solid #ffd276;

    .sumType {
      color: #fff;
      border-radius: 9rpx;
      padding: 8rpx 12rpx;
      margin-bottom: 10px;
    }

    .sumType1 {
      background-color: #25d48b;
    }

    .sumType2 {
      background-color: #ec692b;
    }

    .wares {
      background-color: #f5f5f5;
      border-radius: 9px;
      margin: 10px 0;
      padding: 10rpx;

      .commodity {
        padding: 0 5px;
        width: calc(100% - 55px);

        .name {
          font-size: 14px;
        }

        .num {
          height: 50%;
        }
      }

      .img {
        width: 55px;
        height: 60px;
        // background: #986f6f;
        border-radius: 9px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
        }
      }


      .waresData {
        .title {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        view {
          color: #ec692b;
          font-size: 16px;
          line-height: 30px;
          height: 100%;
        }
      }
    }

    .settle {
      .text {
        font-size: 14px;

        .num {
          font-size: 18px;
          font-weight: bold;
          margin-left: 6rpx;
        }
      }
    }
  }
}
</style>

